<?php

namespace app\minichakra\controller\v1;

use app\common\cachemodel\AppConfig;
use app\common\cachemodel\chakra\ChakraTestRecord;
use app\minichakra\controller\ChakraAuth;

class Test extends ChakraAuth
{
    // public $testCycle = 30 * 86400; // 天
    public $testCycle = 0; // 天

    /**
     * 脉轮 测试首页
     * @return \think\response\Json
     * @throws \Exception
     */
    public function index()
    {
        //  可以 测试
        $remainingDays = 0;
        if ($this->user)
        {
            $lastTestData = (new ChakraTestRecord())->getLastTestData($this->user['id']);
            if ($lastTestData && $this->testCycle > 0)
            {
                $lastTestTime = $lastTestData['create_time'] ?? 0;
                $t = time() - $lastTestTime;    // 距离上次测试时间差
                $remaining = $this->testCycle - $t;
                // 向上取整
                $remainingDays = $remaining > 0 ? ceil($remaining / 86400) : 0;
            }
        }

        return show(config('code.success'), '请求成功', ['remaining_days' => $remainingDays]);
    }

    /**
     * 获取 脉轮测试题目信息
     * @return \think\response\Json
     */
    public function getQuestionInfo()
    {
        $chakraQuestionData = config('chakra_test_question.question_list');

        $optionList = [
            [
                'title' => '没有',
                'value' => 1,
            ], [
                'title' => '很少',
                'value' => 2,
            ], [
                'title' => '偶尔',
                'value' => 3,
            ], [
                'title' => '经常',
                'value' => 4,
            ], [
                'title' => '总是',
                'value' => 5,
            ],
        ];
        shuffle($chakraQuestionData);
        $resData = [];
        foreach ($chakraQuestionData as $datum)
        {
            $resData[] = [
                'id' => $datum['id'],
                'question' => $datum['question'],
                'checked' => 0,
                'option_list' => $optionList,
            ];
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 提交 脉轮测试结果
     * @return \think\response\Json
     * @throws \Exception
     */
    public function toAnswer()
    {
        $answer = input('answer/s', '');
        if (empty($answer))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $chakraQuestionData = config('chakra_test_question');
        $questionNum = count($chakraQuestionData['question_list']);
        $resultData = json_decode($answer, true);
        if (!$resultData || count($resultData) !== $questionNum)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $resAnswerData = [];
        foreach ($resultData as $datum)
        {
            if (!in_array($datum['checked'], [1, 2, 3, 4, 5]))
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            $resAnswerData[$datum['id']] = [
                'id' => $datum['id'],
                'checked' => $datum['checked'],
            ];
        }

        if (count($resAnswerData) !== $questionNum)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $chakraTestRecordModel = new ChakraTestRecord();
        $lastTestData = $chakraTestRecordModel->getLastTestData($this->user['id']);
        if ($lastTestData && $this->testCycle > 0)
        {
            $lastTestTime = $lastTestData['create_time'] ?? 0;
            $t = $this->request->time() - $lastTestTime;    // 距离上次测试时间差
            $remaining = $this->testCycle - $t;
            if ($remaining > 0)
            {
                return show(config('code.error'), '请' . ceil($remaining / 86400) . '天后再测试～');
            }
        }

        $resultData = [
            [
                'type' => 0,
                'score' => 0,
            ], [
                'type' => 1,
                'score' => 0,
            ], [
                'type' => 2,
                'score' => 0,
            ], [
                'type' => 3,
                'score' => 0,
            ], [
                'type' => 4,
                'score' => 0,
            ], [
                'type' => 5,
                'score' => 0,
            ], [
                'type' => 6,
                'score' => 0,
            ],
        ];
        foreach ($chakraQuestionData['question_list'] as $questionItem)
        {
            $aData = $resAnswerData[$questionItem['id']];
            $score = $aData['checked'] - 3;
            $resultData[$questionItem['type']]['score'] += $score;
        }

        $insertData = [
            'uid' => $this->user['id'],
            'answer_data' => json_encode(['answer' => $resAnswerData, 'result' => $resultData,], true),
            'create_time' => $this->request->time(),
        ];

        $id = $chakraTestRecordModel->SaveData($insertData);

        return show(config('code.success'), '请求成功', ['id' => $id]);
    }

    public function getTestResult()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $chakraTestRecordModel = new ChakraTestRecord();
        $detail = $chakraTestRecordModel->getInfoById($id);
        if (!$detail)
        {
            return show(config('code.error'), '服务异常，测试记录不存在');
        }
//        if ($detail['uid'] !== $this->user['id'])
//        {
//            return show(config('code.error'), '暂不支持查看他人测试结果');
//        }
        $chakraQuestionData = config('chakra_test_question');
        $resData = [];
        foreach ($detail['answer_data']['result'] as $item)
        {
            if (!isset($chakraQuestionData['type_list'][$item['type']]))
            {
                continue;
            }
            $chakraTypeData = $chakraQuestionData['type_list'][$item['type']];
            $score = (int)($item['score'] / 16 * 100);
            switch (true)
            {
                case $score > 50:
                    $desc = $chakraTypeData['desc_list'][4];
                    $status = '过度活跃';
                    break;
                case $score > 0:
                    $desc = $chakraTypeData['desc_list'][3];
                    $status = '已开启';
                    break;
                case $score > -50:
                    $desc = $chakraTypeData['desc_list'][2];
                    $status = '不活跃';
                    break;
                default:
                    $desc = $chakraTypeData['desc_list'][1];
                    $status = '封闭';
            }
            $resData[] = [
                'name' => $chakraTypeData['name'],
                'color1' => $chakraTypeData['color1'],
                'color2' => $chakraTypeData['color2'],
                'score' => $score,
                'status' => $status,
                'desc' => $desc,
                'chakras' => $chakraTypeData['chakras'],
            ];
        }
        if ($this->headers['app-type'] === 'TT')
        {
            $chakraConfig = (new AppConfig())->configInfo('chakra_config');
            $resData = [
                'data' => $resData,
                'tt_im_id' => $chakraConfig['tt_im_id'] ?? '',
            ];
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取 脉轮测试列表
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getTestList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 15);

        $chakraTestRecordModel = new ChakraTestRecord();
        $pageData = $chakraTestRecordModel->getListIds($this->user['id'], $page, $limit);

        $testListData = $chakraTestRecordModel->batchGetInfoByIds(array_keys($pageData['data']), ['id', 'create_time']);
        $resData = [];
        foreach ($pageData['data'] as $id => $item)
        {
            if (!isset($testListData[$id]))
            {
                continue;
            }
            $resData[] = [
                'id' => $id,
                'title' => '脉轮测试',
                'time' => date('Y-m-d H:i', $testListData[$id]['create_time']),
            ];
        }

        $pageData['data'] = $resData;

        return show(config('code.success'), '请求成功', $pageData);
    }
}
